// pages/present/present.js
const host = require('../../config.js').host;
const network = require('../../utils/network.js');
const graceChecker = require('../../utils/graceChecker.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    storePhotoList: [],
    expiryDate:'',
    goods: {
      goodsType:'1', //'商品类型0实物1优惠券2抵扣券3广告',
      name: "5元抵扣券",    // 商品名称
      price: '12',  // 商品价格
      costPrice:'5',  // 商品成本价
      totalStock: '999',  // 商品库存数量
      expiryDate: '', // 有效期
      goodsImage: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3598171639,1151740348&fm=26&gp=0.jpg',
    },
    ownerList: [{ //合作的业主
      "ownerId": -1,
      "ownerName": 'woshi yezhu1'
    },
    {
      "ownerId": -2,
      "ownerName": 'woshi 业主2'
    },

  ],
  ownerIndex: -1, // 选中业主的索引
  checkOwnerId: -1, // 选中的业主
  userType: '-1', // 用户类型

  },

// 获取选中的业主
bindPickerChange1(e) {
  console.log('picker发送选择改变，携带值为', e.detail.value);
  // goods_owner_id
  let checkedOwner = this.data.ownerList[e.detail.value];
  if ("undefined" != typeof (checkedOwner)) {
    this.setData({
      ownerIndex: e.detail.value,
      checkOwnerId: checkedOwner.ownerId,
      'goods.goodsOwnerId': checkedOwner.ownerId,
    })
  }

},
// 获取合作的业主
getOwnerList() {

  network.requestGet("/xcx/customer-relation/merchant-owner-list", {
    'isBinding': '1',
    'relationType': '0',

  }, res => {
    this.setData({
      ownerList: res.data.data,
    });
    console.log("ownerList", this.data.ownerList);
    //this.data.ownerList = res.data.data;
  });

},
// 添加 商品提交
formSubmit: function (e) {
  let ownerId = this.data.ownerId;

  this.data.goods.name = e.detail.value.name;
  this.data.goods.price = e.detail.value.price;
  this.data.goods.costPrice = e.detail.value.costPrice;
  this.data.goods.expiryDate = this.data.expiryDate;
  this.data.goods.totalStock = e.detail.value.totalStock;
  //this.data.goods.goodsImage = e.detail.value.goodsImage;

  // 校验参数
  let goods = this.data.goods;
  const params = e.detail.value
  var rule = [ // 表单的字段 校验
    {
      name: "name",
      checkType: "notnull",
      checkRule: "",
      errorMsg: "请输入优惠券名称"
    },
    {
      name: "price",
      checkType: "xiaoshu2",
      checkRule: "",
      errorMsg: "请输入正确的物品价格,小数位2位"
    },
    {
      name: "costPrice",
      checkType: "xiaoshu2",
      checkRule: "",
      errorMsg: "请输入正确商品成本价,小数位2位"
    },
    {
      name: "totalStock",
      checkType: "notnull",
      checkRule: "",
      errorMsg: "请输入总库存数量"
    },
    {
      name: "expiryDate",
      checkType: "notnull",
      checkRule: "",
      errorMsg: "请输入活动有效期"
    },
    //{name:"goodsImage", checkType : "notnull", checkRule:"",  errorMsg:"请添加商品图片"},
  ];
  //校验表单
  var checkRes = graceChecker.check(params, rule);
  if (!checkRes) {
    wx.showToast({
      title: graceChecker.error,
      icon: "none"
    });
    return;
  }
   // 判断用户 类型
   if(1 == this.data.userType){ // 如果是商家添加商品 需要有合作的业主
    let goodsOwnerId = this.data.goods.goodsOwnerId;
    if(0 == goodsOwnerId){
      wx.showToast({
        title: '请选择合作的业主,再添加物品',
        icon: "none"
      });
      return;
    }

  }
  // 业主添加商品
  if (0 == this.data.userType) {// 如果是业主添加商品 需要有合作的商家--从全局获取
    this.data.goods.goodsMerchantId = getApp().globalData.ownerCarryMerchantId;
  }


  network.requestPost("/xcx/goods/add", this.data.goods, res => {
    let resData = res.data;
    setTimeout(function () {
      wx.switchTab({
        url: '/pages/index/index',
      })
    }, 800)
  });
},
 // 选中日期
 DateChange(e) {
  this.setData({
    expiryDate: e.detail.value
  })
},
  // 选图片
  ChooseImage() {
    let that = this;
    let formData = this.data.formData;
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      success: function (res) {
        network.uploadFileLoading("/common/upload", res.tempFiles[0].path, res => {
          let data = JSON.parse(res.data);
          let servicePath = data.fileName;
          let imgUrl = host + servicePath;
          that.data.goods.goodsImage = servicePath;
          that.setData({
            formData: formData,
            storePhotoList: [imgUrl]
          })
        })
      }
    });
  },

  // 图片回显
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.storePhotoList,
      current: e.currentTarget.dataset.url
    });
  },

  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.storePhotoList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            storePhotoList: this.data.storePhotoList
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOwnerList();
     
    this.setData({
      userType: getApp().globalData.userType,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})